package com.binbai.login;

import com.alibaba.fastjson.JSON;
import com.binbai.db.SpringDB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import javax.swing.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * WebServlet注解，映射路径为/LoginServlet
 */
@Component
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
  //自动加载springDB对象
    @Autowired
    private SpringDB springDB;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request请求对象，封装了所有的请求信息
        //response响应对象，
        //输出用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try {
//            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//            JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
//            System.out.println(jdbcTemplate);
            JdbcTemplate jdbcTemplate = springDB.getJdbcTemplate();
            String sql = "select * from t_user where name = '" + username + "' and pass = '" + password + "' and state=0";
            //使用模版查询，返回list列表
            List list = jdbcTemplate.queryForList(sql);

            Map map = new HashMap();
            if (list.size()>0){
                map.put("result", "success");
            }else{
                map.put("result", "error");
            }
            //map转成JSON字符串
            String s = JSON.toJSONString(map);
            //响应数据
            response.getWriter().write(s);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
